package com.yuanli.cosmeticmirror.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class GeneralUtils {


    /**
     * 得到当前时间
     */
    public static String getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        // new Date()为获取当前系统时间
        return df.format(new Date());
    }

//    /**
//     * 获得app签名
//     *
//     * @param params
//     * @return
//     */
//    public static String genAppSign(List<NameValuePair> params) {
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < params.size(); i++) {
//            sb.append(params.get(i).getName());
//            sb.append('=');
//            sb.append(params.get(i).getValue());
//            sb.append('&');
//        }
//        sb.append("key=");
//        sb.append(WXConstants.API_KEY);
//        LogUtils.i("app签名", "genAppSign: " + sb.toString());
//        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
//        LogUtils.i("app签名", appSign);
//        return appSign;
//    }

    /**
     * 毫秒 转 hh:mm:ss 时间转化
     *
     * @return
     */
    public static String millisecondToStr2(int millisecond) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        df.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        try {
            return df.format(new Date(millisecond));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "00:00:00";
    }

    /**
     * 毫秒 转 mm:ss 时间转化
     *
     * @return
     */
    public static String millisecondToStr(int millisecond) {
        SimpleDateFormat df = new SimpleDateFormat("mm:ss", Locale.CHINA);
        df.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        try {
            return df.format(new Date(millisecond));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "00:00";
    }

    /**
     * 音乐时长毫秒
     *
     * @param musicPath
     * @return
     */
    public static int getMusicSumTime(String musicPath) {
        int duration = 1;
        MediaPlayer mediaPlayer = null;
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(musicPath);
            mediaPlayer.prepare();
            duration = mediaPlayer.getDuration();
            mediaPlayer.release();
        } catch (Exception e) {
            e.printStackTrace();
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
        }
        return duration;
    }

    /**
     * 得到当前时间戳
     */
    public static long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public static void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

    /**
     * double 留两位小数
     *
     * @param f
     * @return
     */
    public static double getDoubleValue(double f) {
        BigDecimal bg = new BigDecimal(f);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    /**
     * 比较date1-date2差几天
     *
     * @return
     */
    public static int dateDiff(String dateStr1, String dateStr2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d1 = df.parse(dateStr1);
            Date d2 = df.parse(dateStr2);
            long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
            int days = (int) (diff / (1000 * 60 * 60 * 24));
            return days;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取版本信息
     *
     * @return
     * @throws Exception
     */
    public static String getVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String versionName = info.versionName;
        return versionName;
    }

//    /**
//     * 检查是否登录
//     *
//     * @param context
//     * @param pagePath
//     * @return 是否登录
//     */
//    public static boolean checkToken(Context context, String pagePath) {
//        if (getToken(context)) {
//            return true;
//        } else {
//            ARouter.getInstance().build(ARouterPaths.MINE_LOGIN).withString("pagePath", pagePath).navigation();
//            return false;
//        }
//    }
//
//    /**
//     * @param context
//     * @return 是否登录
//     */
//    public static boolean getToken(Context context) {
//        return new BaseSharedPreference(context, "isLogin").getBoolean("isLogin", false);
//    }

    /**
     * 加密
     * 32位大写加密
     *
     * @param plaintext 明文
     * @return ciphertext 密文
     */
    public final static String toMd5(String plaintext) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = plaintext.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).toUpperCase();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 删除指定目录下文件及目录
     *
     * @param deleteThisPath
     * @param filePath
     * @return
     */
    public static boolean deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) { // 如果下面还有文件
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) { // 如果是文件，删除
                        file.delete();
                    } else { // 目录
                        if (file.listFiles().length == 0) { // 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSizes(File f) {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                try {
                    size = size + getFileSize(flist[i]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return size;
    }

    /**
     * 获取指定文件大小  B
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFileSize(File file) {
        long size = 0;
        try {
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } else {
                file.createNewFile();
                Log.e("获取文件大小", "文件不存在!");
            }
            return size;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String formetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        }
        return fileSizeString;
    }

    /**
     * 获取cache路径
     *
     * @param context
     * @return
     */
    public static String getDiskCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        } else {
            return context.getCacheDir().getAbsolutePath();
        }
    }


//    /**
//     * 获取缓存File路径
//     *
//     * @param context
//     * @return
//     */
//    public static String getCacheFilePath(Context context, int type) {
//        String path = null;
//        switch (type) {
//            case BaseConstants.MUSIC:
//                String musicPath;
//                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
//                    musicPath = context.getExternalFilesDir("bgMusic").getPath();
//                } else {
//                    musicPath = context.getFilesDir().getAbsolutePath() + File.separator + "bgMusic";
//                    FileUtils.createDirs(musicPath);
//                }
//                path = musicPath;
//                break;
//        }
//
//
//        return path;
//    }


    /**
     * 生成随机数
     * String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
     */
    public static String getRandom(int num) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }


    /**
     * 判断字符串是否为null或者0长度，字符串在判断长度时，先去除前后的空格,空或者0长度返回false,否则返回true
     *
     * @param str 被判断的字符串
     * @return boolean
     */
    public static boolean isNotNullOrZeroLength(String str) {
        return !isNullOrZeroLength(str);
    }

    /**
     * @param str 被判断的字符串
     * @return boolean
     */
    public static boolean isNullOrZeroLength(String str) {
        return (null == str || "".equals(str.trim())) ? true : false;
    }

    /**
     * 判断集合对象是否为null或者0大小 , 为空或0大小返回false, 否则返回true
     *
     * @param c collection 集合接口
     * @return boolean 布尔值
     * @see [类、类#方法、类#成员]
     */
    public static boolean isNotNullOrZeroSize(Collection<? extends Object> c) {
        return !isNullOrZeroSize(c);
    }

    public static boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    /**
     * 判断集合对象是否为null或者0大小 , 为空或0大小返回true ,否则返回false
     *
     * @param c collection 集合接口
     * @return boolean 布尔值
     * @see [类、类#方法、类#成员]
     */
    public static boolean isNullOrZeroSize(Collection<? extends Object> c) {
        return isNull(c) || c.isEmpty();
    }

    /**
     * 判断对象是否为null , 为null返回true,否则返回false
     *
     * @param obj 被判断的对象
     * @return boolean
     */
    public static boolean isNull(Object obj) {
        return (null == obj) ? true : false;
    }

    /**
     * <手机号码判断>
     *
     * @param tel
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean isTel(String tel) {
        if (tel == null) {
            return false;
        }
        if (tel.length() != 11) {
            return false;
        }
        //  String str = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147))\\d{8}$";
        //   Pattern p = Pattern.compile(str);
        //   Matcher m = p.matcher(tel);
        return true;
    }

    public static boolean isNotTel(String tel) {
        return !isTel(tel);
    }

    /**
     * 字符串传Json
     *
     * @param names
     * @param strs
     * @return
     */

    public static String getJson(String[] names, String[] strs) {
        StringBuilder result = new StringBuilder("{\"");
        for (int i = 0; i < strs.length; i++) {
            result = result.append(names[i] + "\"");
            result = result.append(":\"");
            result = result.append(strs[i] + "\"");
            if (i < strs.length - 1)
                result = result.append(",\"");
        }
        result = result.append("}");
        return result.toString();
    }

    /**
     * 得到随机字符串
     */
    public static String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    /**
     * 得到当前时间戳
     */
    public static long getTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 毫秒 转 yy-MM-dd hh:mm  时间转化
     *
     * @return
     */
    public static String millisecondToStr3() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        try {
            return df.format(new Date(System.currentTimeMillis()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "2019-01-01 00:00:00";
    }

    /**
     * 毫秒 转 yy-MM-dd hh:mm  时间转化
     *
     * @return
     */
    public static String millisecondToStr4() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss", Locale.CHINA);
        try {
            return df.format(new Date(System.currentTimeMillis()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "2019-01-01 00:00:00";
    }


    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b 字节数组
     * @return 字符串
     */

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

    /**
     * 获取设备ID
     *
     * @return
     */
    public static String getDeviceId(Context context) {
        String deviceId = "";
        try {
            deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (SecurityException ex) {
            ex.printStackTrace();
        }
        return deviceId;
    }

    /**
     * 手机型号
     *
     * @return
     */
    public static String getBrand(Context context) {
        return Build.BRAND;
    }

//    public static String getUsername(Context context) {
//        return new BaseSharedPreference(context, "username").getString("username", null);
//    }
//
//    public static String getNickname(Context context) {
//        return new BaseSharedPreference(context, "nickname").getString("nickname", null);
//    }
//
//    public static void setVipDay(Context context, int vipDay) {
//        new BaseSharedPreference(context, "vipDay").saveInt("vipDay", vipDay);
//    }
//
//    public static int getVipDay(Context context) {
//        return new BaseSharedPreference(context, "vipDay").getInt("vipDay", 0);
//    }
//
//    public static void saveUsername(Context context, String username) {
//        new BaseSharedPreference(context, "username").saveString("username", username);
//    }
//
//
//    public static void saveNickname(Context context, String nickname) {
//        new BaseSharedPreference(context, "nickname").saveString("nickname", nickname);
//    }

    public static String getAppName(Context context) {
        return "化妆镜";
    }

    public static String millSecondToTime(int millSecond) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String hms = formatter.format(millSecond);
        return hms;
    }


    /**
     * @param bMute 值为true时为关闭背景音乐。
     */
    @TargetApi(Build.VERSION_CODES.FROYO)
    public static boolean muteAudioFocus(Context context, boolean bMute) {
        if (context == null) {
            Log.d("ANDROID_LAB", "context is null.");
            return false;
        }
        boolean bool;
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (bMute) {
            int result = am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
        } else {
            int result = am.abandonAudioFocus(null);
            bool = result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
        }
//        LogUtils.d("ANDROID_LAB", "pauseMusic bMute=" + bMute + " result=" + bool);
        return bool;
    }

    /**
     * 复制文本到剪贴板
     *
     * @param context
     * @param text
     */
    public static void copyToClipboard(Context context, String text) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", text);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            Toast.makeText(context, "已复制到剪切板", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(context, "复制失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    public static String getDate() {
        Date now = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        return ft.format(now);
    }

//    public static void setStatusBar(Activity activity, int colorId) {
//        ImmersionBar.with(activity)
//                .statusBarColor(colorId)     //状态栏颜色，不写默认透明色
//                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
//                .init();
//    }

    /**
     * 是否为 mm:ss 格式的时间
     *
     * @return
     */
    public static boolean isTime(String time) {
        Pattern p = Pattern.compile("/^(0\\d{1}|1\\d{1}|2[0-3]):([0-5]\\d{1})$/");
        // 需要要判断的字符串;
        Matcher m = p.matcher(time);
        return m.matches();
    }

}
